package com.atguigu.day04;

import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Example6 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.addSource(new SourceFunction<Tuple2<String, Long>>() {
            @Override
            public void run(SourceContext<Tuple2<String, Long>> ctx) throws Exception {
                ctx.collect(Tuple2.of("a", 1000L));
                Thread.sleep(1000L);
                ctx.collect(Tuple2.of("a", 2000L));
                Thread.sleep(1000L);
                ctx.collect(Tuple2.of("a", 3000L));
                Thread.sleep(1000L);
                ctx.collect(Tuple2.of("a", 1000L));
            }

            @Override
            public void cancel() {

            }
        })
                .assignTimestampsAndWatermarks(
                        new CustomerWaterStrategy()
                )
                .keyBy(x -> x.f0)
                .process(new KeyedProcessFunction<String, Tuple2<String, Long>, String>() {
                    @Override
                    public void processElement(Tuple2<String, Long> value, Context ctx, Collector<String> out) throws Exception {
                        if (ctx.timestamp() < ctx.timerService().currentWatermark()) {
                            out.collect("数据迟到了" + value + "时间是：" + ctx.timestamp());
                        } else {
                            out.collect("正常数据：" + value + "时间是:" + ctx.timestamp());
                        }
                    }
                })
                .print();

        env.execute();
    }
    public static class CustomerWaterStrategy implements WatermarkStrategy<Tuple2<String, Long>> {

        @Override
        public WatermarkGenerator<Tuple2<String, Long>> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {
            return new WatermarkGenerator<Tuple2<String, Long>>() {
                private final long delay = 0L;
                private Long maxTs = -Long.MAX_VALUE+delay+1;

                @Override
                public void onEvent(Tuple2<String, Long> stringLongTuple2, long l, WatermarkOutput watermarkOutput) {
                    maxTs = Math.max(maxTs,stringLongTuple2.f1);
                }

                @Override
                public void onPeriodicEmit(WatermarkOutput watermarkOutput) {
                    watermarkOutput.emitWatermark(new Watermark(maxTs - delay - 1L));
                }
            };
        }

        @Override
        public TimestampAssigner<Tuple2<String, Long>> createTimestampAssigner(TimestampAssignerSupplier.Context context) {
            return new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                @Override
                public long extractTimestamp(Tuple2<String, Long> element, long recordTimestamp) {
                    return element.f1;
                }
            };
        }
    }
}
